package de.tum.in.eist.im.client;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.core.client.GWT;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.util.Calendar;

import de.tum.in.eist.im.client.domain.Message;
import de.tum.in.eist.im.client.domain.User;

public class EIST_IM_CHAT extends EIST_IM_LOGIN {
	
	int buildHandler = 0;
	
	
	public EIST_IM_CHAT() {
		// infoCloseBox initialize
		infoCloseBoxPanel
				.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		infoCloseBox.add(infoCloseBoxPanel);
		infoCloseBoxPanel.add(infoCloseBoxLabel);
		infoCloseBoxPanel.add(infoCloseBoxButton);
		infoCloseBoxButton.setText("Close");
		infoCloseBox.setAnimationEnabled(true);
		infoCloseBox.setGlassEnabled(true);
		infoCloseBoxButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				infoCloseBox.hide();

			}
		});
		buildChat();
	}
	// -------------- Chat --------------

	private VerticalPanel chatDesktopPanel = new VerticalPanel();
	private HorizontalPanel HorizontalChatPanel = new HorizontalPanel();
	private HorizontalPanel Footer = new HorizontalPanel();
	private HorizontalPanel Header = new HorizontalPanel();
	private TextBox SendMessageTextBox = new TextBox();
	private TabPanel TabedChatroom = new TabPanel();
	private FlexTable ChatroomTable = new FlexTable();
	private FlexTable Userlist = new FlexTable();
	private FlexTable ReceivedMessages = new FlexTable();
	private Label ChatTitle = new Label("EIST-IM Masters of Chatbusiness!");
	private Button LogoutButton = new Button("Logout");
	private HorizontalPanel UserlistReceivePanel = new HorizontalPanel();
	private VerticalPanel SendMessagesPanel = new VerticalPanel();
	private Button SendMessageButton = new Button("Send");
	private HorizontalPanel SendingMessagesPanel = new HorizontalPanel();
	private Button SwitchButton = new Button("Switch");
	private Button deleteChatTabButton = new Button(" X");
																	// main Panel
																	// for
																	// Desktop
	private TabPanel chatMobilePanel = new TabPanel(); // main Panel for Mobile
	private VerticalPanel chatMobileChatroomPanel = new VerticalPanel();
	private VerticalPanel chatMobileChatPanel = new VerticalPanel();
	private VerticalPanel chatMobileUserlistPanel = new VerticalPanel();
	private VerticalPanel chatMobileSettingsPanel = new VerticalPanel();
																		// Panel
																		// for
																		// the
																		// tab
																		// with
																		// sending/receiving
																		// messages

	// Data structure
	private List<User> loggedInUsers;

	// Keywords for mobile browsers
	static final String[] MOBILE_SPECIFIC_SUBSTRING = { "iPhone", "Android",
			"MIDP", "Opera Mobi", "Opera Mini", "BlackBerry", "HP iPAQ",
			"IEMobile", "MSIEMobile", "Windows Phone", "HTC", "LG", "MOT",
			"Nokia", "Symbian", "Fennec", "Maemo", "Tear", "Midori", "armv",
			"Windows CE", "WindowsCE", "Smartphone", "240x320", "176x220",
			"320x320", "160x160", "webOS", "Palm", "Sagem", "Samsung", "SGH",
			"SIE", "SonyEricsson", "MMP", "UCWEB" };

	/**
	 * Check the userAgent of the Browser of the User for keywords, which
	 * indicates that the used browser is a mobile device browser.
	 * 
	 * @return true if a keyword for mobile browser was find
	 */
	  private boolean isMobileBrowser() { String userAgent = Window.Navigator.getUserAgent();
	  
	  for (String mobile: MOBILE_SPECIFIC_SUBSTRING){ if
	  (userAgent.contains(mobile) || userAgent.contains(mobile.toUpperCase())
	  || userAgent.contains(mobile.toLowerCase())){ return true; } }
	  
	  return false; }
	 
	/**
	 * After successful Login this Method must be activated. The Method builds
	 * and creates the GUI for the Chat room.
	 */
	  private void buildChat() { 
		  if (isMobileBrowser()) 
			  buildMobileChat(); 
		  else
			  buildDesktopChat();
	  }
	 
	/**
	 * Builds the Chat room for normal Desktop Browsers
	 */
	private void buildDesktopChat() {
		// removes the login screen and Associate the new Main panel with the
		// HTML host page.
		RootPanel.get("chat").remove(loginPanel);
		RootPanel.get("chat").add(chatDesktopPanel);

		// only to see if it works
		useInfoCloseBox("Desktop is loading..", "Please Wait!/n" + Window.Navigator.getUserAgent(), true);
		
		chatDesktopPanel.setWidth("100%");
		chatDesktopPanel.setHeight("100%");
		chatDesktopPanel.setStyleName("chatstyle");
		chatDesktopPanel.add(Header);
				Header.add(ChatTitle);
				Header.setWidth("100%");
				Header.setCellHorizontalAlignment(ChatTitle, HasHorizontalAlignment.ALIGN_JUSTIFY);
				Header.setStyleName("Chattitle");
		
		chatDesktopPanel.add(HorizontalChatPanel);
		
				HorizontalChatPanel.setWidth("100&");
				
				HorizontalChatPanel.add(ChatroomTable);
				HorizontalChatPanel.setCellHorizontalAlignment(ChatroomTable, HasHorizontalAlignment.ALIGN_CENTER);
				ChatroomTable.setText(0, 0, "Chatroomlist");
				ChatroomTable.setWidth("20%");
				ChatroomTable.setHeight("100%");
				ChatroomTable.getRowFormatter().addStyleName(0, "ListHeader");
				ChatroomTable.setStyleName("liststyle");
				
				HorizontalChatPanel.add(TabedChatroom);
				HorizontalChatPanel.setWidth("100%");
						TabedChatroom.setWidth("100%");
						TabedChatroom.add(UserlistReceivePanel,"Chatroom1");
						TabedChatroom.add(new Label("You fool, do you think we got this already!"),"Chatroom2" + deleteChatTabButton.getText().toString());
						TabedChatroom.add(new Label("You fool, do you think we got this already!"),"Chatroom3" + deleteChatTabButton.toString());
						TabedChatroom.add(new Label("You fool, do you think we got this already!"),"Chatroom4" + deleteChatTabButton.toString());
						TabedChatroom.add(new Label("You fool, do you think we got this already!"),"Chatroom5" + deleteChatTabButton.toString());
						TabedChatroom.selectTab(0);
						
						
							UserlistReceivePanel.setWidth("100%");
							UserlistReceivePanel.setHeight("100%");
							UserlistReceivePanel.add(SendMessagesPanel);
							UserlistReceivePanel.setCellHorizontalAlignment(SendMessagesPanel, HasHorizontalAlignment.ALIGN_LEFT);
									
							
									SendMessagesPanel.setHeight("100%");
									SendMessagesPanel.setWidth("100%");
									SendMessagesPanel.setStyleName("chatstyle");
									SendMessagesPanel.add(ReceivedMessages);
									SendMessagesPanel.setCellVerticalAlignment(ReceivedMessages, HasVerticalAlignment.ALIGN_TOP);
											
											ReceivedMessages.setText(0,0,"Newsstream");
									SendMessagesPanel.add(SendingMessagesPanel);
									SendMessagesPanel.setCellWidth(SendingMessagesPanel, "100%");
									SendingMessagesPanel.setCellVerticalAlignment(SendingMessagesPanel, HasVerticalAlignment.ALIGN_BOTTOM);
										
												SendingMessagesPanel.setWidth("100%");
												SendingMessagesPanel.setStyleName("sendingmessages");
												SendingMessagesPanel.add(SendMessageTextBox);
													SendMessageTextBox.setWidth("100%");
												SendingMessagesPanel.setCellWidth(SendMessageTextBox, "94%");
												SendingMessagesPanel.setCellWidth(SendMessageButton, "10%");
												SendingMessagesPanel.add(SendMessageButton);
													SendMessageTextBox.setFocus(true);
												SendingMessagesPanel.setCellVerticalAlignment(SendMessageButton, HasVerticalAlignment.ALIGN_MIDDLE);
												SendingMessagesPanel.setCellHorizontalAlignment(SendMessageTextBox, HasHorizontalAlignment.ALIGN_LEFT);
												SendingMessagesPanel.setCellHorizontalAlignment(SendMessageButton, HasHorizontalAlignment.ALIGN_RIGHT);
													
							
							UserlistReceivePanel.add(Userlist);
							UserlistReceivePanel.setCellHorizontalAlignment(Userlist, HasHorizontalAlignment.ALIGN_CENTER);
							
									Userlist.setText(0,0,"Userlist");
									Userlist.setStyleName("chatstyle");
				
					HorizontalChatPanel.setStyleName("chatstyle");
		
		buildHandler++;
									
		chatDesktopPanel.add(Footer);
		Footer.add(SwitchButton);
		
				deleteChatTabButton.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
							TabedChatroom.remove(deleteChatTabButton.getParent());
						
					}
				});

				ClickHandler SendMessage = new 	ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						int row = ReceivedMessages.getRowCount();
						String message;
						message = SendMessageTextBox.getText().toString();
						ReceivedMessages.setText(row,0, message);
						SendMessageTextBox.setText("");
					}
				};
				
		
		SendMessageButton.addClickHandler(SendMessage);

						
				/**
				 * KeyPress Handler for Sending User Messages by pressing ENTER
				 */
		 // Listen for keyboard events in the input box.
	    SendMessageTextBox.addKeyPressHandler(new KeyPressHandler() {
	      public void onKeyPress(KeyPressEvent event) {
	        if (event.getCharCode() == KeyCodes.KEY_ENTER && SendMessageTextBox.getText() != null) {
	        	int row = ReceivedMessages.getRowCount();
				String message;
				message = SendMessageTextBox.getText().toString();
				ReceivedMessages.setText(row,0, message);
				SendMessageTextBox.setText("");
	        }
	      }
	    });
		
				SwitchButton.addClickHandler(new ClickHandler() {
					

					@Override
					public void onClick(ClickEvent event) {
						chatDesktopPanel.setVisible(false);
						if(buildHandler <2){
						buildMobileChat();
						}
						else{
						chatMobilePanel.setVisible(true);
						
						ChatroomTable.setVisible(true);
						Userlist.setVisible(true);
						LogoutButton.setVisible(true);
						SwitchButton.setVisible(true);
						ReceivedMessages.setVisible(true);
						SendingMessagesPanel.setVisible(true);
					}
					}
				});
				
		Footer.add(LogoutButton);
			
		Footer.setWidth("100%");
		Footer.setCellHorizontalAlignment(LogoutButton,HasHorizontalAlignment.ALIGN_RIGHT);
		Footer.setStyleName("footerstyle");
		
		
		ChatTitle.setStyleName("Chattitle");
		
		
		//closing/hiding InfoCloseBox
		
		infoCloseBox.hide();
		
		LogoutButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				logoutUser(chatDesktopPanel);
			
				
			}
		});
		
	} // buildDesktopChat()

	/**
	 * Builds the chat room for mobile Browsers
	 */
	private void buildMobileChat() {
		// removes the login screen and Associate the new Main panel with the
		// HTML host page.

		// only to see if it works
		super.useInfoCloseBox("Mobile", "Mobile Version", true);
		useInfoCloseBox("Mobile", "Mobile Version" + Window.Navigator.getUserAgent(), true);

		// TODO: Finish mobile
		
		RootPanel.get("chat").remove(loginPanel);
		RootPanel.get("chat").add(chatMobilePanel);

		chatMobilePanel.add(chatMobileChatroomPanel, "Chatrooms");
		chatMobilePanel.selectTab(0);
			chatMobileChatroomPanel.add(ChatroomTable);
		chatMobilePanel.add(chatMobileChatPanel,"Chat");
			chatMobileChatPanel.add(ReceivedMessages);
			chatMobileChatPanel.add(SendingMessagesPanel);
		chatMobilePanel.add(chatMobileUserlistPanel,"Userlist");
				chatMobileUserlistPanel.add(Userlist);
		chatMobilePanel.add(chatMobileSettingsPanel, "Settings");
				chatMobileSettingsPanel.add(LogoutButton);
				//TODO: not geting it! chatMobileSettingsPanel.add(SwitchButton);
			
		buildHandler++;
		
				SwitchButton.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						chatMobilePanel.setVisible(false);
						if(buildHandler <2){
						buildDesktopChat();
						}
						else{
						chatDesktopPanel.setVisible(true);
						
						ChatroomTable.setVisible(true);
						Userlist.setVisible(true);
						LogoutButton.setVisible(true);
						SwitchButton.setVisible(true);
						ReceivedMessages.setVisible(true);
						SendingMessagesPanel.setVisible(true);
						}
						
					}
				});
			
		infoCloseBox.hide();
		
		LogoutButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				logoutUser(chatMobilePanel);
				
			}
		});
	} // buildMobileChat()
	
	/**
	 * initialise the User list, who are logged in. This method should only
	 * fires on sturtup. the LoggedInUsers will be cleared and then request 
	 * a List from the server.
	 * @param flexTable will be cleared an then build
	 */
	private void initialiseLoggedInUserList(final FlexTable flexTable) {
		
		flexTable.clear();
		loggedInUsers.clear();
			proxy.getLoggedInUsers(new AsyncCallback<List<User>>() {
			
			@Override
			public void onFailure(Throwable caught) {
				useInfoCloseBox("Error", "User List could not build. Pleas logout and try again!", true);
			}

			@Override
			public void onSuccess(List<User> result) {
				
				Iterator<User> it = result.iterator();
				
				while (it.hasNext()) {
					User curUser = it.next();
					flexTable.add(new Label(curUser.getUsername()));
					loggedInUsers.add(curUser);
				}
				
				}
		});
	}
	
	/**
	 * Removes a user from the Lists, who has logged out
	 * @param user removing User
	 * @param flexTable removing user from here
	 */
	private void removeLoggedInUser(User user, FlexTable flexTable) {
		int index = loggedInUsers.indexOf(user);
		loggedInUsers.remove(user);
		flexTable.removeRow(index);
	}
	
	/**
	 * Adds a User to the Lists
	 * @param user adding user
	 * @param flexTable add user to here
	 */
	private void addLoggedInUser(User user, FlexTable flexTable) {
		loggedInUsers.add(user);
		flexTable.add(new Label(user.getUsername()));
	}
	
	/**
	 * Sends a String as Message to the Server.
	 * @param msg The Massage
	 */
	private void sendMsg(String msg){
		
		proxy.sendMessage(new Message(Calendar.getInstance().getTime().getTime()
				, msg, loggedInUser), new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						useInfoCloseBox("Error", "Sending Massage failed!", true);
					}

					@Override
					public void onSuccess(Void result) {
						// TODO nothing
						
					}
				});
	}
	
	/**
	 * Adds a Message to the Lists
	 * @param flexTable The FlexTable where to add
	 * @param lst The List where to add
	 * @param msg The Message
	 */
	private void addToMsgList(FlexTable flexTable, List<Message> lst, Message msg) {
			// if there are too many Messages in the List
		if (lst.size() > 200) {
			lst.remove(0);
			flexTable.removeRow(0);
		}
		
		lst.add(msg);
		flexTable.add(new Label(msg.getText()));
	}
	

	
//	private void initializeMsgList(FlexTable flexTable) {
//		Date dt = new Date();
//	}

}

